// serialportDlg.cpp : implementation file
//

#include "stdafx.h"
#include "serialport.h"
#include "serialportDlg.h"
#include "SerialPortC.h"
typedef unsigned char UINT8;
typedef unsigned short UINT16;
typedef unsigned int UINT32;
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSerialportDlg dialog

CSerialportDlg::CSerialportDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CSerialportDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CSerialportDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CSerialportDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSerialportDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CSerialportDlg, CDialog)
	//{{AFX_MSG_MAP(CSerialportDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
	ON_BN_CLICKED(IDC_BUTTON3, OnButton3)
	ON_BN_CLICKED(IDC_BUTTON2, OnButton2)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_BUTTON4, OnButton4)
	ON_MESSAGE(WM_COMM_RXCHAR, OnRxChar)
	ON_BN_CLICKED(IDC_BUTTON5, OnButton5)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSerialportDlg message handlers

BOOL CSerialportDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	SetDlgItemInt(IDC_PORTNUM,61);
	SetDlgItemInt(IDC_BAUD,115200);
	SetDlgItemInt(IDC_TIMERGAP,500);
	SetDlgItemInt(IDC_KEY,0xab);
	SetDlgItemInt(IDC_ID,0x14);
	freopen("D:\\output.txt", "w+", stdout);
	OnButton3();//load templete
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CSerialportDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CSerialportDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CSerialportDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

CSerialPort sp;
UINT8 buffer[20 * 1024];
#define REMOTE_MAC_0 0x00000000
UINT8 templete[4][3620];
UINT8 deviceID[4] = { 0 };
UINT8 authCode[4] = { 0x12,0x56,0x98,0xab };
UINT8 authKey = 0;
int sendState = 0;
UINT32 OSComport = 6;
INT32 ackok = 0;
/*
*	cmd: 0 head, 1 data, 2 tail,3 time
*	fseq: 0..3
*	pseq: 0..3
*/
void prepareData(UINT8* buffer, int* len, UINT8 cmd, UINT8 fseq, UINT16 pseq) {
	static UINT16 seq = 0;
	UINT16 u16len = 0;
	UINT16 checksum = 0;
	int i=0;
	buffer[0] = 0xaa;
	buffer[1] = 0x55;

	buffer[3] = seq&0xff;
	buffer[4] = (seq>>8) & 0xff;

	buffer[7] = deviceID[0];
	buffer[8] = deviceID[1];
	buffer[9] = deviceID[2];
	buffer[10] = deviceID[3];

	buffer[11] = authCode[0];
	buffer[12] = authCode[1];
	buffer[13] = authCode[2];
	buffer[14] = authCode[3];

	switch (cmd) {
	case 0:
		u16len = 22;
		buffer[2] = 0;
		buffer[15] = 4;	//total finger num
		buffer[16] = 4;
		buffer[17] = 0;
		buffer[18] = 4;
		buffer[19] = 0;
		buffer[20] = 4;
		buffer[21] = 0;
		buffer[22] = 4;
		buffer[23] = 0;
		break;
	case 1:
		u16len = 905 + 16;
		buffer[2] = 1;
		buffer[15] = fseq+1;
		buffer[16] = pseq & 0xff;
		buffer[17] = (pseq >> 8) & 0xff;
		for (i = 0; i < 905; i++) {
			buffer[18 + i] = templete[fseq][905 * pseq+i];
		}
		break;
	case 2:
		u16len = 13;
		buffer[2] = 2;
		break;
	case 3:
		break;
	default:
		break;
	}
	buffer[5] = u16len & 0xff;
	buffer[6] = (u16len >> 8) & 0xff;
	for (i = 2; i < u16len+2; i++) {
		buffer[i] ^= authKey;
		checksum += buffer[i];
	}
	buffer[u16len + 2] = checksum & 0xff;
	buffer[u16len + 3] = (checksum >> 8) & 0xff;
	//
	seq++;
	*len = u16len + 4;
}
void CSerialportDlg::OnButton1() 
{
	// TODO: Add your control notification handler code here
	int port = GetDlgItemInt(IDC_PORTNUM);	//1 to 4
	int baud = GetDlgItemInt(IDC_BAUD);
	int r = sp.InitPort(this, port, 115200);
	if (!r) {
		CString cs;
		cs.Format("serial port init Fail!");
		SetDlgItemText(IDC_STATUS, cs);
		return;
	}
	r = sp.StartMonitoring();
	if (!r) {
		sp.StopMonitoring();
		CString cs;
		cs.Format("serial port open Fail!");
		SetDlgItemText(IDC_STATUS, cs);
		return;
	}
	CString cs;
	cs.Format("serial port open success!");
	SetDlgItemText(IDC_STATUS, cs);
}

void CSerialportDlg::OnButton3() 
{
	// TODO: Add your control notification handler code here
	FILE* fp;
	if ((fp = fopen("D:\\MCU\\fingerprint\\Data\\templete1.bin", "rb")) != 0) {
		fread(templete[0], 1, 3620, fp);
		fclose(fp);
	}
	else printf("error open file templete1.bin\r\n");
	
	if ((fp = fopen("D:\\MCU\\fingerprint\\Data\\templete2.bin", "rb")) != 0) {
		fread(templete[1], 1, 3620, fp);
		fclose(fp);
	}
	else printf("error open file templete2.bin\r\n");

	if ((fp = fopen("D:\\MCU\\fingerprint\\Data\\templete3.bin", "rb")) != 0) {
		fread(templete[2], 1, 3620, fp);
		fclose(fp);
	}
	else printf("error open file templete3.bin\r\n");

	if ((fp = fopen("D:\\MCU\\fingerprint\\Data\\templete4.bin", "rb")) != 0) {
		fread(templete[3], 1, 3620, fp);
		fclose(fp);
	}
	else printf("error open file templete4.bin\r\n");
}

void CSerialportDlg::OnButton2() 
{
	// TODO: Add your control notification handler code here
	int gap = GetDlgItemInt(IDC_TIMERGAP);
	SetTimer(1,gap,NULL);
}

void CSerialportDlg::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	int u16len = 0;
	UINT8 fseq = 0;
	UINT16 pseq = 0;
	UINT8 cmd = 0;
	if (sendState == 0) {	//head
		cmd = 0;
	}else if (sendState >= 1 && sendState <= 16) {	//data
		cmd = 1;
		fseq = (sendState - 1) / 4;
		pseq = (sendState - 1) % 4;
	}else if (sendState == 17) {	//tail
		cmd = 2;
	}else {
		sendState = 0;
		KillTimer(nIDEvent);
		return;
	}
	prepareData(reinterpret_cast<UINT8*>(buffer), &u16len, cmd,fseq,pseq);

	if(ackok ==1){	//if no ack, go on send this pack; if ack ok, send next pack
		sendState++;
		ackok = 0;
	}
	if (nIDEvent == 1) {	//serial port timer
#if 1
		char filename[256];
		sprintf(filename, "D://%d_%d_%d.txt", cmd,fseq, pseq);
		FILE* fp;
		fp = fopen(filename, "w+");
		for (int i = 0; i < u16len; i++) {
			fprintf(fp, "0x%x ", (unsigned char)buffer[i]);
			if (i % 10 == 0) fprintf(fp,"\r\n");
		}
		fclose(fp);
#endif
		sp.WriteToPort(reinterpret_cast<char*>(buffer), u16len);
	}
	CString cs;
	cs.Format("send data: length: %d,state:%d,data: 0x%x,0x%x,..."
		, u16len, sendState, buffer[0], buffer[1]);
	SetDlgItemText(IDC_STATUS, cs);
	CDialog::OnTimer(nIDEvent);
}

void CSerialportDlg::OnButton4() 
{
	// TODO: Add your control notification handler code here
	sp.StopMonitoring();
	//sp.ClosePort();
}
LRESULT CSerialportDlg::OnRxChar(WPARAM ch,LPARAM port){
	unsigned char* buffer = reinterpret_cast<unsigned char*>(ch);	//18 length
	CString cs;
	CString t;
	int i;
	for (i = 0;i<18;i++){
		t.Format("0x%x,",buffer[i]);
		cs+=t;
	}
	SetDlgItemText(IDC_STATUS2, cs);
	if(buffer[0]==0xaa
		&&buffer[1]==0x55){	//ack ok
		ackok = 1;
	}
	return 0;
}

void CSerialportDlg::OnButton5() 
{
	// TODO: Add your control notification handler code here
	authKey = GetDlgItemInt(IDC_KEY);
	
	UINT32 ID = GetDlgItemInt(IDC_ID);
	deviceID[0]= ID&0xff;
	deviceID[1]=(ID>>8)&0xff;
	deviceID[2]=(ID>>16)&0xff;
	deviceID[3]=(ID>>24)&0xff;
}
